package com.css.zfzx.fwsjcj.modules.reinforce.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.base.response.RestResponse;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.zfzx.fwsjcj.cache.DivisionCache;
import com.css.zfzx.fwsjcj.commen.util.ImageByteUtil;
import com.css.zfzx.fwsjcj.commen.util.ZipUtils;
import com.css.zfzx.fwsjcj.modules.analysis.vo.AnalysisQueryVo;
import com.css.zfzx.fwsjcj.modules.reinforce.entity.FwReinforceEntity;
import com.css.zfzx.fwsjcj.modules.reinforce.service.FwReinforceService;
import com.css.zfzx.fwsjcj.modules.reinforce.vo.CheckVO;
import com.css.zfzx.fwsjcj.modules.reinforce.vo.QueryVO;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.vo.GeneralQueryVo;
import com.css.zfzx.fwsjcj.modules.taskmanage.taskfrom.vo.GeneralVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author leon
 * @Title:
 * @Description: 房屋设施加固工程调查控制层
 * @date 2020/8/27 10:25
 */
@RestController
@RequestMapping("/fw/reinforce")
@Slf4j
public class FwReinforceController {
    @Autowired
    private FwReinforceService reinforceService;

    /**
     * 新增：暂存或者保存
     *
     * @param projectType     0加固工程，1新建工程
     * @param type            0暂存，1保存
     * @param reinforceEntity
     * @return
     */
    @PostMapping("save/{projectType}/{type}")
    public RestResponse save(@PathVariable String projectType, @PathVariable String type, @RequestBody FwReinforceEntity reinforceEntity) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            // 设置项目类型的值
            reinforceEntity.setProjectType(projectType);
            reinforceService.save(type, reinforceEntity);
            jsonObject.put("message", "保存成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "保存失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 修改
     *
     * @param reinforceEntity
     * @return
     */
    @PostMapping("update")
    public RestResponse update(@RequestBody FwReinforceEntity reinforceEntity) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            reinforceService.update(reinforceEntity);
            jsonObject.put("message", "修改成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "修改失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 多条件分页查询
     *
     * @param queryVO
     * @param request
     * @return
     */
    @GetMapping("page/{projectType}")
    public RestResponse getPage(@PathVariable String projectType, QueryVO queryVO, HttpServletRequest request) {
        RestResponse restResponse = null;
        try {
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            JSONObject jsonObject = reinforceService.getPage(projectType, queryVO, curPage, pageSize);
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "查询失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 查看详情
     *
     * @param id
     * @return
     */
    @GetMapping("getone/{id}")
    public RestResponse getOne(@PathVariable String id) {
        RestResponse restResponse = null;
        try {
            FwReinforceEntity one = reinforceService.getOne(id);
            restResponse = RestResponse.succeed(one);
        } catch (Exception e) {
            String errormessage = "查询失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }


    /**
     * 批量提交
     *
     * @param ids
     * @return
     */
    @PostMapping("/submit")
    public RestResponse submit(@RequestBody String ids) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            List<String> idList = Arrays.asList(ids.split(","));
            reinforceService.submit(idList);
            jsonObject.put("message", "提交成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "提交失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/del")
    public RestResponse delete(@RequestBody String ids) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            List<String> idList = Arrays.asList(ids.split(","));
            reinforceService.delete(idList);
            jsonObject.put("message", "删除成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "删除失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 批量审核
     *
     * @param checkVO
     * @return
     */
    @PostMapping("/check")
    public RestResponse check(@RequestBody CheckVO checkVO) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            List<String> idList = Arrays.asList(checkVO.getIds().split(","));
            reinforceService.check(idList, checkVO.getStatus(), checkVO.getReason());
            jsonObject.put("message", "审核成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "审核失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 单个审核
     *
     * @param reinforceEntity 可以修改表单并且审核
     * @return
     */
    @PostMapping("checkone")
    public RestResponse checkone(@RequestBody FwReinforceEntity reinforceEntity) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            reinforceService.update(reinforceEntity);
            jsonObject.put("message", "审核成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = "审核失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 获取工程编号
     *
     * @return
     */
    @GetMapping("projectCode")
    public RestResponse getProjectCode() {
        RestResponse restResponse = null;
        try {
            String num = DivisionCache.reinforceCode();
            restResponse = RestResponse.succeed(num);
        } catch (Exception e) {
            String errormessage = "获取失败";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }


    /**
     * 导出判断是否为空
     *
     * @param queryVO
     * @return
     */
    @GetMapping("/isEmpty")
    public RestResponse isEmpty(@ModelAttribute QueryVO queryVO) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            Boolean isEmpty = reinforceService.isEmpty(queryVO);
            if (isEmpty) {
                jsonObject.put("message", "是");
            } else {
                jsonObject.put("message", "否");
            }
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 导出: 根据请求参数导出
     *
     * @param queryVO
     * @param response
     * @return
     */
    @GetMapping("/export")
    public RestResponse export(@ModelAttribute QueryVO queryVO, HttpServletResponse response) {
        RestResponse restResponse = null;
        JSONObject jsonObject = new JSONObject();
        try {
            reinforceService.export(queryVO, response);
            jsonObject.put("message", "导出成功");
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 打包压缩下载文件
     */
    @GetMapping(value = "/downLoadZipFile")
    public void downLoadZipFile(String projectType, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String zipName = "图片压缩包.zip";
        zipName = URLEncoder.encode(zipName, "UTF-8");
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
        // 跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Method", "POST,GET");
        // 输出流
        ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
        try {
            // 定义根路径
            String rootPath = request.getServletContext().getRealPath(File.separator);
            // 临时文件路径
            String path = rootPath + "\\temp_download";
            File tempfile = new File(path);
            if (!tempfile.exists()) {
                tempfile.mkdir();
            }
            // 获取图片路径
            List<String> paths = reinforceService.listImagesByType(projectType);
            for (String pa : paths) {
                //调用工具类获取图片
                byte[] data = ImageByteUtil.image2byte(pa);
                //new一个文件对象用来保存图片，默认保存当前工程根目录
                if (data != null) {
                    String fileName = pa.substring(pa.lastIndexOf("/"));
                    File imageFile = new File(path + File.separator + fileName);
                    //创建输出流
                    FileOutputStream outStream = new FileOutputStream(imageFile);
                    //写入数据
                    outStream.write(data);
                    //关闭输出流
                    outStream.close();
                }
            }
            // 创建文件
            File inFile = new File(path);
            File[] files = inFile.listFiles();
            // 遍历读取临时路径下的文件，导出为压缩包
            if (files != null && files.length > 0) {
                for (File file : files) {
                    String path1 = file.getPath();
                    ZipUtils.doCompress(path1, out);
                    response.flushBuffer();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();
            // 输出客户端结束后，删除临时文件夹以及下面的图片与压缩包
            String rootPath = request.getServletContext().getRealPath(File.separator);
            String path = rootPath + "\\temp_download";
            File inFile = new File(path);
            File[] files = inFile.listFiles();
            if (inFile.exists()) {
                for (File file : files) {
                    file.delete();
                }
                inFile.delete();
            }
        }
    }

    @GetMapping("getForm")
    public RestResponse findForm() {
        JSONObject jsonObject = new JSONObject();
        RestResponse restResponse = null;
        try {
            List<FwReinforceEntity> reinforceServiceForm = reinforceService.findForm();
            jsonObject.put("message", "查询成功");
            restResponse = RestResponse.succeed(reinforceServiceForm);
        } catch (Exception e) {
            String errorMessage = "查询失败";
            restResponse = RestResponse.fail(errorMessage);
        }
        return restResponse;
    }

    /**
     * 工程柱状图
     *
     * @param queryVO
     * @return
     */
    @GetMapping("projectBarNum")
    public RestResponse projectNumBar(QueryVO queryVO) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            Map<String, Object> data = new HashMap<>();
            // 项目类型：0加固工程，1新建工程
            // 加固工程数量
            queryVO.setProjectType("0");
            long reCount = reinforceService.count(queryVO);
            // 新建工程数量
            queryVO.setProjectType("1");
            long newCount = reinforceService.count(queryVO);
            // X轴数据
            ArrayList<String> x = new ArrayList<>();
            x.add("加固工程");
            x.add("新建工程");
            // Y轴数据
            ArrayList<Long> y = new ArrayList<>();
            y.add(reCount);
            y.add(newCount);
            data.put("x", x);
            data.put("y", y);
            // 返回数据
            json.put("data", data);
            json.put("message", "查询成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }


    /**
     * 工程饼状图
     *
     * @param queryVO
     * @return
     */
    @GetMapping("projectPieNum")
    public RestResponse projectNumPie(QueryVO queryVO) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            ArrayList<Map> data = new ArrayList<>();
            // 项目类型：0加固工程，1新建工程

            // 加固工程数量
            queryVO.setProjectType("0");
            long reCount = reinforceService.count(queryVO);
            HashMap<String, Object> reMap = new HashMap<>();
            reMap.put("value", reCount);
            reMap.put("name", "加固工程");
            data.add(reMap);

            // 新建工程数量
            queryVO.setProjectType("1");
            long newCount = reinforceService.count(queryVO);
            HashMap<String, Object> newMap = new HashMap<>();
            newMap.put("value", newCount);
            newMap.put("name", "新建工程");
            data.add(newMap);

            // 返回数据
            json.put("data", data);
            json.put("message", "查询成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }


    /**
     * 工程类别饼状图
     *
     * @param queryVO
     * @return
     */
    @GetMapping("projectPieNumByCategory")
    public RestResponse projectPieNumByCategory(QueryVO queryVO) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            List<Map> data = reinforceService.projectPieNumByCategory(queryVO);
            // 返回数据
            json.put("data", data);
            json.put("message", "查询成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            response = RestResponse.fail(errorMessage);
        }
        return response;
    }

    /**
     * 工程年份查询
     *
     * @param queryVO
     * @return
     */
    @GetMapping("/reinforceyear")
    public RestResponse findByYear(QueryVO queryVO) {
        JSONObject jsonObject = new JSONObject();
        RestResponse restResponse = null;
        try {
            List<Map> barByYear = reinforceService.findBarByYear(queryVO);
            jsonObject.put("reinforceYear", barByYear);
            restResponse = RestResponse.succeed(jsonObject);
        } catch (Exception e) {
            String errorMessage = "查询失败";
            restResponse = RestResponse.fail(errorMessage);
        }
        return restResponse;
    }

    /**
     * 展示所有省数据
     *
     * @param queryVO
     * @return
     */
    @GetMapping("/provices")
    public RestResponse provices(QueryVO queryVO) {
        RestResponse restResponse = null;
        try {
            List<HashMap> maps = reinforceService.listProvices(queryVO);
            restResponse = RestResponse.succeed(maps);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 展示所有市数据
     *
     * @param queryVO
     * @return
     */
    @GetMapping("/cities")
    public RestResponse cities(QueryVO queryVO) {
        RestResponse restResponse = null;
        try {
            List<HashMap> maps = reinforceService.listCities(queryVO);
            restResponse = RestResponse.succeed(maps);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 展示所有区数据
     *
     * @param queryVO
     * @return
     */
    @GetMapping("/areas")
    public RestResponse areas(QueryVO queryVO) {
        RestResponse restResponse = null;
        try {
            List<HashMap> maps = reinforceService.listAreas(queryVO);
            restResponse = RestResponse.succeed(maps);
        } catch (Exception e) {
            String errormessage = e.getMessage();
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }
}
